package com.fxnotes.common.ui;



import javafx.scene.control.ContentDisplay;
import javafx.scene.control.ListCell;
import javafx.scene.control.TextField;

public abstract class EditableListCell<T> extends ListCell<T> {

    final TextField textField;

    public EditableListCell(TextField textField) {
        this.textField = textField;
    }

    @Override
    public void startEdit() {
        super.startEdit();

        textField.setText(getText());
        setGraphic(textField);
        setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
    }

    @Override
    public void updateItem(T item, boolean empty) {
        super.updateItem(item, empty);

        if (empty) {
            setText(null);
            setGraphic(null);

        } else {
            if (isEditing()) {
                if (item != null) {
                    setText(item.toString());
                }
                setGraphic(textField);
                setContentDisplay(ContentDisplay.GRAPHIC_ONLY);

            } else {
                setText(getCellString());
                setContentDisplay(ContentDisplay.TEXT_ONLY);
            }
        }
    }

    @Override
    public void commitEdit(T item) {
        super.commitEdit(item);

        setText(item.toString());
        setGraphic(null);
        setContentDisplay(ContentDisplay.TEXT_ONLY);
        
        changed(item);
    }

    @Override
    public void cancelEdit() {
        super.cancelEdit();

        setText(getCellString());
        setGraphic(null);
        setContentDisplay(ContentDisplay.TEXT_ONLY);
    }

    private String getCellString() {
        return getItem() == null ? "" : getItem().toString();
    }
    
    public abstract String getString(T item);
    
    public abstract void changed(T item);
}